package com.wx.forum.controller;

import com.wx.forum.common.AppResult;
import com.wx.forum.common.ResultCode;
import com.wx.forum.contant.Contants;
import com.wx.forum.model.Message;
import com.wx.forum.model.User;
import com.wx.forum.service.IMessageService;
import com.wx.forum.service.IUserService;
import com.wx.forum.utils.JwtUtil;
import com.wx.forum.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Api(tags = "站内信接口")
@RequestMapping("/message")
@RestController
@Slf4j
public class MesssageController {
    @Resource
    private IMessageService messageService;
    @Resource
    private IUserService userService;

    @ApiOperation("发送私信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam("接收方id") @RequestParam("receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam("私信内容") @RequestParam("content") @NonNull String content) {
        //1.1判断用户是否处于禁言状态
        //通过token获取id

        String token = request.getHeader(Contants.USER_TOKEN_HANDER);
        Long userId = JwtUtil.getIdByToken(token);
        if (userId == null || StringUtil.isEmpty(token)) {

            //打印信息
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        User user = userService.selectById(userId);
        if (user.getState() == 1) {
            //用户已经禁言
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //1.2判断是否自己给自己发
        if (userId == receiveUserId) {
            return AppResult.failed("不能给自己发送私信");
        }

        //2.校验接收者是否存在
        User receiveUser = userService.selectById(receiveUserId);
        if (receiveUser == null) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }

        //3.创建站内信对象
        Message message = new Message();
        message.setContent(content);
        message.setPostUserId(userId);
        message.setReceiveUserId(receiveUserId);
        //4.调用service
        messageService.create(message);
        log.info("站内信发送成功" + userId + "->" + receiveUserId + "");
        return AppResult.success("发送成功");
    }

    @ApiOperation("获取未读私信数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        //1.通过token获取id
        String token = request.getHeader(Contants.USER_TOKEN_HANDER);
        Long userId = JwtUtil.getIdByToken(token);
        if (userId == null || StringUtil.isEmpty(token)) {

            //打印信息
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //2.调用dao
        Integer count = messageService.selectUnreadCount(userId);
        return AppResult.success(count);
    }

    @ApiOperation("根据receiveUserId查询站内信列表")
    @GetMapping("/getByReceiveId")
    public AppResult<List<Message>> getByReceiveId(HttpServletRequest request) {
        //1.通过token获取id
        String token = request.getHeader(Contants.USER_TOKEN_HANDER);
        Long receiveUserId = JwtUtil.getIdByToken(token);
        if (receiveUserId == null || StringUtil.isEmpty(token)) {

            //打印信息
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //2.调用dao
        List<Message> messageList = messageService.selectByReceiveId(receiveUserId);
        return AppResult.success(messageList);
    }

    @ApiOperation("更新站内信状态")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,
                              @ApiParam("站内信id") @RequestParam("id") @NonNull Long id) {
        //1.判断站内信是否合法
        Message message = messageService.selectById(id);
        if (message == null || message.getDeleteState() == 1 || message.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //2.判断站内信是不是自己的
        //通过token获取id
        String token = request.getHeader(Contants.USER_TOKEN_HANDER);
        Long userId = JwtUtil.getIdByToken(token);
        if (userId == null || StringUtil.isEmpty(token)) {

            //打印信息
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        if (userId != message.getReceiveUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //3.调用service,把状态更新为已读
        messageService.updateStateById(id, (byte) 1);
        return AppResult.success();
    }

    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("要回复的站内信的id") @RequestParam("repliedId") @NonNull Long repiledId,
                           @ApiParam("回复的内容") @RequestParam("content") @NonNull String content) {
        //1.校验站内信是否存在
        Message existsMessage = messageService.selectById(repiledId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            //打印信息
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());
            //抛出异常
            return AppResult.success(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //2.校验用户状态
        //通过token获取id
        String token = request.getHeader(Contants.USER_TOKEN_HANDER);
        Long userId = JwtUtil.getIdByToken(token);
        if (userId == null || StringUtil.isEmpty(token)) {

            //打印信息
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        User user = userService.selectById(userId);
        if (user == null || user.getState() == 1) {
                return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //不能自己给自己回复
        if(userId == existsMessage.getPostUserId()){
            return AppResult.failed("不能自己给自己回复");
        }
        //3.构建新增站内信对象
        Message message = new Message();
        message.setContent(content);
        message.setPostUserId(userId);
        message.setReceiveUserId(existsMessage.getPostUserId());

        messageService.reply(repiledId, message);
        return AppResult.success();
    }

}
